<template>
  <div class="user-chat">
    <van-nav-bar title="小智同学" left-arrow @click-left="$router.back()">
    </van-nav-bar>

    <van-cell-group class="message-list" ref="message-list">
      <van-cell v-for="(msg, index) in messages" :key="index">
        <template :slot="msg.send ? 'right-icon' : 'icon'">
          <van-image
            round
            :src="
              msg.send ? user_photo : 'https://img01.yzcdn.cn/vant/cat.jpeg'
            "
          />
        </template>
        <div
          slot="title"
          class="title"
          :class="{ 'title-right': msg.send, 'title-left': !msg.send }"
        >
          {{ msg.msg }}
        </div>
      </van-cell>
    </van-cell-group>

    <van-cell-group class="send-message-wrap">
      <van-field v-model="message" placeholder="请输入消息" />
      <van-button @click="onSend" type="primary" size="small">发送</van-button>
    </van-cell-group>
  </div>
</template>

<script>
import { mapState } from "vuex";
import io from "socket.io-client";
import { v4 as uuidv4 } from "uuid";
import { getItem, setItem } from "@/utils/storage";
import { getUserProfile } from "@/api/user";

export default {
  name: "UserChat",
  data() {
    return {
      user_photo: "", // 用户头像
      message: "", //输入的消息
      socket: null, // WebSocket通信对象
      messages: getItem("chat-message") || [], // 消息列表
    };
  },
  watch: {
    messages(newVal) {
      setItem("chat-message", newVal);

      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },
  },
  computed: {
    ...mapState(["user"]),
  },
  methods: {
    // 点击发送
    onSend() {
      const data = {
        msg: this.message,
        timestamp: Date.now(),
      };

      this.socket.emit("message", data);

      data.send = true;
      this.messages.push(data);

      this.message = "";
    },
    // 对话框滚动到最底部
    scrollToBottom() {
      const list = this.$refs["message-list"];
      list.scrollTop = list.scrollHeight;
    },
    // 获取用户信息
    async loadUserPhoto() {
      const { data } = await getUserProfile();
      this.user_photo = data.data.photo;
    },
  },
  created() {
    this.loadUserPhoto();

    this.socket = io("http://toutiao.itheima.net", {
      query: {
        token: this.user.token || uuidv4(),
      },
      transports: ["websocket"],
    });

    this.socket.on("message", (data) => {
      this.messages.push(data);
    });
  },
  mounted() {
    this.scrollToBottom();
  },
};
</script>

<style scoped lang="less">
.message-list {
  position: fixed;
  left: 0;
  right: 0;
  top: 64px;
  bottom: 44px;
  overflow-y: auto;

  .van-cell {
    z-index: 1;

    .van-image {
      height: 40px;
      width: 40px;
    }

    .title {
      box-sizing: border-box;
      display: inline-block;
      max-width: 303px;
      border-radius: 5px;
      height: 100%;
      padding: 8px 8px;
      overflow-wrap: anywhere;
    }

    .title-left {
      margin-left: 5px;
      background-color: skyblue;
    }

    .title-right {
      float: right;
      margin-right: 5px;
      background-color: greenyellow;
    }
  }
}

.send-message-wrap {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  padding: 0 14px 0 0;

  .van-button {
    width: 60px;
  }
}
</style>
